import { NextRequest } from 'next/server'
import OpenAI from 'openai'
import { mysql, redis } from '@/utils/db'

let openai: OpenAI
let model: string = 'gpt-3.5-turbo'

if (process.env.LOC_GPT_URL && false) {
  openai = new OpenAI({
    baseURL: process.env.LOC_GPT_URL,
  })
  model = 'deepseek-r1:1.5b'
} else {
  openai = new OpenAI({
    // baseURL: process.env.OPENAI_BASE_URL || 'https://api.chatanywhere.tech',
    baseURL: 'https://api.chatanywhere.tech',
    apiKey: process.env.OPENAI_API_KEY || '',
  })
}

const pro = {
  role: 'system',
  content:
    '你是一个全能助手，偏向于变成。你的上下文仅供参考，实际问题以最后一条内容为主',
}

const userId = 1
const replaceThink = (str: string) => {
  try {
    return str
      .replace(/<think[^>]*>/gi, '\n:::think\n')
      .replace(/<\/think>/gi, '\n:::\n')
  } catch (error) {
    console.error('Error replacing think:', error)
    return str
  }
}
async function getChatRedisHistory(key: string) {
  try {
    const redis_history = (await redis.get(key)) as string
    const list = JSON.parse(redis_history)
    return list
  } catch (e) {
    return []
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const message = body.message

    if (!message) {
      return new Response(JSON.stringify({ error: 'Message is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      })
    }

    // const redis_history =
    //   (await getChatRedisHistory(`user_${userId}_chatHistory`)) || []
    const redis_history: any = []

    redis_history.push({ role: 'user', content: message })
    redis_history.unshift(pro)

    const res = await mysql.gpt_chat_history.create({
      data: { user_id: 1, message, sender_type: 'user' },
    })

    const stream = new ReadableStream({
      async start(controller) {
        try {
          const completionStream = await openai.chat.completions.create({
            model,
            messages: redis_history,
            stream: true,
          })

          let obj: any = {
            user_id: 1,
            sender_type: 'gpt',
            message: '',
          }

          // think 标签处理缓存
          let text = ''
          for await (const chunk of completionStream) {
            let content = chunk.choices[0]?.delta?.content || ''
            if (!content) continue

            text = replaceThink(content)
            obj.message += text
            obj.message = obj.message.replace(/\n:::think\n\n\n\n:::\n/g, '')
            controller.enqueue(
              new TextEncoder().encode(
                `data: ${JSON.stringify({
                  sendUserInfo: res,
                  sender_type: 'gpt',
                  message: text.replace(/\n:::think\n\n\n\n:::\n/g, ''),
                })}\n\n`
              )
            )
          }
          controller.enqueue(
            new TextEncoder().encode(
              `data: ${JSON.stringify({
                sender_type: 'gpt',
                message:
                  text +
                  '\n\n—— 作者：吴大宝，仅供测试、面试查看。\n\n并发有限，请勿暴力测试\n\n本地部署部署自己gpt请看本人[csdn：https://blog.csdn.net/weixin_68183854?type=blog](https://blog.csdn.net/weixin_68183854?type=blog)',
              })}\n\n`
            )
          )
          await mysql.gpt_chat_history.create({ data: obj })
          redis_history.push({ role: 'system', content: obj.message })
          redis.set(
            'user_1_chatHistory',
            JSON.stringify(redis_history.slice(-10))
          )
        } catch (error: any) {
          console.error('OpenAI API error:', error)
          controller.enqueue(
            new TextEncoder().encode(
              `data: ${JSON.stringify({ error: error.message })}\n\n`
            )
          )
        } finally {
          controller.close()
        }
      },
    })

    return new Response(stream, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        'Access-Control-Allow-Origin': '*',
      },
    })
  } catch (error: any) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    })
  }
}
